import React, {PureComponent} from 'react';
import {Editor} from 'react-draft-wysiwyg';
import { routerRedux,Link } from 'dva/router';
import {connect} from 'dva';
import Spec from './Spec';
import SpecList from './SpecList';
import SpecParams from './SpecParams';
import GroupAdd from './GroupAdd';
import Uploader from './Uploader';
import UploadVideo from './UploadVideo';
//import { EditorState } from 'draft-js';
import MyEditor from './Editor';
import GoodsModal from '../Sales/GoodsModal';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Icon,
  Tooltip,
  Upload,
  Divider,
  Row,
  Col,
  Checkbox,
  Table,
  notification,
  message,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import G from '../../utils/g';

const FormItem = Form.Item;
const {Option} = Select;
const {RangePicker} = DatePicker;
const {TextArea} = Input;


const linkGoodsTip = [
  '随机选择相同分类商品显示',
  '实时显示最新商品',
  '实时显示销量最高的商品',
  '自定义显示商品'
]

// @connect(({ loading }) => ({
//   submitting: loading.effects['form/submitRegularForm'],
// }))
@connect(state => ({
  addGoods: state.addGoods,
}))
@Form.create()



export default class BasicForms extends PureComponent {

  postData = {
    imgs: []
  };

  state = {
    paramsData : [],  //规格参数
    specData: [], //商品规格
    visibleGroupForm: false,
    clearImgs : false,
    selectedGoods : [], //选中的相关商品
    modalVisible : false,
  };

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'addGoods/clear',
    });
  }

  componentDidMount() {
    const {dispatch, location} = this.props;
    this.id = G.getUrlValue('id', location.search);
    if (typeof this.id != 'undefined') {
      dispatch({
        type: 'addGoods/getGoodsDetail',
        payload: {
          id: this.id
        }
      }).then(()=> {
        const goods = {...this.props.addGoods.goods};
        
        let newState = {};
        if(goods.specs){
          newState.specData = goods.specs;

        }
        if(goods.spec_params){
          newState.paramsData = goods.spec_params;
        }
        if(goods.link_info.link_goods){
          newState.selectedGoods = goods.link_info.link_goods;
        }
        this.setState(newState);
        this.postData = goods;
        //除掉表单绑定数据，防止提交时被覆盖
        delete this.postData.categoryId;
        delete this.postData.desc;
        delete this.postData.groups;
        delete this.postData.line_price;
        delete this.postData.price;
        delete this.postData.name;
        delete this.postData.status;
        delete this.postData.video;
        delete this.postData.link_info.model;
      });
    }
    dispatch({
      type: 'addGoods/getCategory',
    });
    dispatch({
      type: 'addGoods/getGroup',
    });
  };

  componentWillReceiveProps(nextProps){
      console.log(nextProps);
      if(nextProps.addGoods.link_goods != this.props.addGoods.link_goods){
        this.setState({
          selectedGoods : nextProps.addGoods.link_goods
        });
      }
  }

  handleSubmit = e => {
    e.preventDefault();
    const { form, location } = this.props;
    console.log(form.getFieldValue('imgs'));
    form.validateFieldsAndScroll((err, values) => {
      console.log('values', values);
      console.log(this.postData);
      let linkGoodsInfo = {
        model : values.link_goods,
      }
      if(linkGoodsInfo.model == 3){  //自定义关联商品
        linkGoodsInfo.link_goods = this.state.selectedGoods.map(v=>v.id);
      }
      let postData = {
        ...values,
        ...this.postData,
        specs: this.state.specData,
        link_info : linkGoodsInfo
      };
      // if (postData.specs_list && Array.isArray(postData.specs_list)) {
      //   postData.specs_list.forEach(v=> {
      //     v.freight = values.express;
      //   });
      // }
      if (G.getUrlValue('id')) {
        postData.id = G.getUrlValue('id', location.search);
      }
      
      if (postData.imgs == '') {
        message.error('商品图片不能为空');
        return;
      }
      if(postData.specs.length == 0){  //无规格值时
        postData.specs_list = [{
          sku : {},
          price : postData.price,
          stock : postData.stock
        }]
      }

      console.log('postData', postData);
      if (!err) {
        this.props.dispatch({
          type: 'addGoods/saveGoods',
          payload: postData,
        });
      }
    });
  };

  bindImgsChange = (file)=> {
    this.postData.imgs = [];
    file.forEach(v=> {
      this.postData.imgs.push(v.url)
    });
    if(file.length == 0){
      this.setState({
        clearImgs : true
      });
    }
    //console.log(this.postData);
  };

  bindVideoChange = (file)=> {
    this.props.dispatch({
      type : 'addGoods/saveVideo',
      payload : {
        url : file[0].url
      }
    });
    this.postData.video = file.length > 0 ? file[0].url : '';
  };

  bindSpcChange = (specData)=> {
    console.log(specData);
    this.setState({
      specData: specData
    });
  };

  bindSpecParamsChange = (data)=> {
    this.postData.spec_params = data;
    this.setState({
      paramsData : data
    });
  };

  bindMyEditorChange = (value)=> {
    this.postData.content = value;
  };

  bindSpecListChange = (data)=> {
    //console.log('speclist',data);
    const {specData} = this.state;
    let specsList = [];
    data.forEach(v=> {
      let sku = {};
      specData.forEach((val, j)=> {
        sku[val.name] = v[j]
      });
      specsList.push({
        sku: sku,
        price: v.price,
        stock: v.stock
      });
    });
    //console.log('specsList',specsList);
    this.postData.specs_list = specsList;
  };

  bindLinkGoods = (value)=>{  //只要select选择，则调用此方法
    console.log(value);
    if(value == -1 || value==3){
      this.setState({
        selectedGoods : []
      });
    }
    if(value == 3){  //手动选择商品
        this.handleModalVisible(true);
    }
  }

  bindChangeLinkGoods = (value)=>{
    this.setState({  //默认清除已有选中的商品数据
      selectedGoods : []
    });
    let payload = {model : value};
    if(value == -1){
      return false;
    }
    if(value == 3){ 
      return false;
    }
    if(this.id){
      payload.id = this.id;
    }
    const categoryId = this.props.form.getFieldValue('categoryId');
    if(value == 0){
      if(categoryId){ //同分类
        payload.categoryId = categoryId
      }else{
        message.error('请先选择分类');
        return false; 
      }
    }
    this.props.dispatch({
      type: 'addGoods/getLinkGoods',
      payload : payload
    });
  }

  bindCategoryChange = (value)=>{
    //分类改变时，相关分类商品也需要修改
    if(this.props.form.getFieldValue('link_goods') == 0){ //同分类
      this.props.dispatch({
      type: 'addGoods/getLinkGoods',
      payload : {
        categoryId : value,
        model : 0
      }
    });
    }
  }

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  changeSelectedGoods = (goods)=>{  //从弹框中获取到选中商品的
    console.log("goods",goods);
    if(goods.length >= 4){ //最多只能选择四个商品
        this.handleModalVisible(false);
    }
    this.setState({
      selectedGoods : goods
    });
  };



  removeSelected = (id)=>{  //移除选中的商品

    if(typeof id == 'undefined'){
      console.error('被移除的商品ID为空');
      return false;
    }
    let selectedGoods = [...this.state.selectedGoods];
    const result = selectedGoods.filter(v => v.id != id);
    //console.log('selectedGoods',selectedGoods, result);
    this.setState({
      selectedGoods : result
    });

  };

  render() {
    const {addGoods : {category, group, goods}, dispatch} = this.props;
    const {paramsData, specData, clearImgs, selectedGoods, modalVisible} = this.state;
    const {getFieldDecorator, getFieldValue} = this.props.form;

    console.log('selectedGoods', selectedGoods);

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 4},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 15},
      },
    };

    const formDetailItemLayout= {
      labelCol: {
        xs: {span: 24},
        sm: {span: 4},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 20},
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };

    let imgsFileList = [];
    if(!clearImgs && Array.isArray(goods.imgs)){
      imgsFileList = goods.imgs.map(v=> {
        const uid = G.uuid(16);
        return {
          uid: uid,
          name: uid,
          status: 'done',
          url: v,
        }
      });
    }

    let videoFileList = [];
    if(goods.video){
      videoFileList.push({
        uid: G.uuid(16),
        status : 'done',
        url: goods.video
      });
    }

    if(goods.specs && goods.specs.length == 0){
      goods.price = goods.specs_list[0].price;
      goods.stock = goods.specs_list[0].stock;
    }

    let columns = [
                      {
                        title: '图片',
                        dataIndex: 'imgs',
                        render(val) {
                          return <img src={`${val[0]}?imageView2/1/w/50`} width={50} />;
                        },
                      },
                      {
                        title: '名称',
                        dataIndex: 'name',
                      },
                      {
                        title: '库存',
                        dataIndex: 'stock_count',
                        align: 'right',
                        render: val => `${val || 0}`,
                      },
                      {
                        title: '价格',
                        dataIndex: 'min_price',
                        align: 'right',
                        render: val => `${val || 0}元`,
                      },
                      
                    ];
                      if(getFieldValue('link_goods') == 3){
                        columns.push({
                        title: '操作',
                        render: (text,records)=> {
                          return <a onClick={()=>{this.removeSelected(text.id)}}>移除</a>
                        }
                      });
    }


    return (
      <PageHeaderLayout
        title="商品管理"
        content="商品新增或修改"
      >
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} style={{marginTop: 8}}>
            <FormItem {...formItemLayout} label="商品名称">
              {getFieldDecorator('name', {
                initialValue: goods.name,
                rules: [
                  {
                    required: true,
                    message: '请给商品请个名字吧',
                  },
                ],
              })(<Input placeholder="给商品请个名字吧"/>)}
            </FormItem>
            <FormItem {...formItemLayout} label="商品描述">
              {getFieldDecorator('desc', {
                initialValue: goods.desc,
                rules: [
                  {
                    message: '请输入对商品的描述',
                  },
                ],
              })(
                <TextArea
                  style={{minHeight: 32}}
                  placeholder="请输入对商品的描述"
                  rows={4}
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="商品图片" help="最多上传15张 规格（800*800）">
              {getFieldDecorator('imgs', {
                initialValue: imgsFileList,
                rules: [
                  {
                    required: true,
                    message: '请上传商品图片',
                  },
                ],
              })(
                <Uploader
                  length={15}
                  fileList={imgsFileList}
                  onChange={this.bindImgsChange}
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="商品类目">
              {getFieldDecorator('categoryId', {
                initialValue: goods.categoryId,
                rules: [
                  {
                    required: true,
                    message: '请给商品选个分类吧',
                  },
                ],
              })(
                <Select placeholder="请选择所属行业类目" style={{width: '100%'}} onChange={this.bindCategoryChange}>
                  {
                    category.map(v=> {
                      return <Option value={v.id} key={v.id}>{v.name}</Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="商品分组">
              {getFieldDecorator('groups', {
                initialValue: goods.groups,
              })(
                <Select
                  mode="multiple"
                  style={{width: '100%'}}
                  placeholder="Please select"
                >
                  {
                    group.map(v=> {
                      return <Option value={v.name} key={v.name}>{v.name}</Option>
                    })
                  }
                </Select>
              )}

              <GroupAdd dispatch={dispatch}/>
            </FormItem>
            <FormItem {...formItemLayout} label="主图视频" help={`建议时长9-30秒，建议视频宽高比16:9，以mp4格式为准`}>
              {getFieldDecorator('video', {})(
                <UploadVideo onChange={ this.bindVideoChange } fileList={ videoFileList }/>
              )}
            </FormItem>
            <Divider></Divider>
            <FormItem {...formItemLayout} label="商品规格">
              <Spec onChange={this.bindSpcChange} defaultValue={specData}  />
            </FormItem>
            <FormItem {...formItemLayout} label="规格明细" style={{display: specData.length == 0 ? 'none' : 'block'}}>
              <SpecList data={specData} specList={goods.specs_list || []} onChange={this.bindSpecListChange} dispatch={dispatch}/>
            </FormItem>
            {
              specData.length == 0 ? <FormItem {...formItemLayout} label="价格">
                {getFieldDecorator('price', {
                  initialValue: goods.price,
                  rules: [
                    {
                      required: true,
                      message: '请填写统一商品价格',
                    },
                  ],
                })(<Input placeholder="统一商品价格"></Input>)}
              </FormItem> : null
            }

            <FormItem {...formItemLayout} label="划线价">
              {getFieldDecorator('line_price', {
                initialValue: goods.line_price,
              })(<Input placeholder="商品划线价格"></Input>)}
            </FormItem>
            {
              specData.length == 0 ? <FormItem {...formItemLayout} label="库存">
                {getFieldDecorator('stock', {
                  initialValue: goods.stock,
                  rules: [{
                    required : true,
                    message : '请填写商品库存'
                  }]
                })(<Input placeholder="0"></Input>)}
              </FormItem> : null
            }

            {/*<FormItem {...formItemLayout} label="快递运费">
              {getFieldDecorator('express', {
                initialValue: goods.express,
                rules: [
                  {
                    required: true,
                    message: '请填写快递运费',
                  },
                ],
              })(<Input placeholder="0"></Input>)}
            </FormItem>*/}
            <FormItem {...formItemLayout} label="上架状态">
              {
                getFieldDecorator('status', {
                  initialValue: goods.status || 1,
                })(
                  <Radio.Group>
                    <Radio value={1}>立即上架</Radio>
                    <Radio value={0}>暂不售卖，放入仓库</Radio>
                  </Radio.Group>
                )
              }
            </FormItem>
            <FormItem {...formItemLayout} label="相关商品类型">
              {
                getFieldDecorator('link_goods', {
                  initialValue: goods.link_info.model || 0,
                })(
                  <Select onSelect={this.bindLinkGoods} onChange={this.bindChangeLinkGoods}>
                    <Option value={0}>同类商品</Option>
                    <Option value={1}>最新商品</Option>
                    <Option value={2}>最热商品</Option>
                    <Option value={3}>手动选择</Option>
                    <Option value={-1}>不显示</Option>
                  </Select>
                )
              }
              <div className="ant-form-explain">{
                linkGoodsTip[getFieldValue('link_goods')]
              }</div>
              {
                selectedGoods.length > 0 ? <Table
                    style={{marginTop: '8px'}}
                    pagination = {false}
                    columns={columns}
                    dataSource={selectedGoods}
                    rowKey="id"
                  ></Table> : '暂无相关商品'
              }
              
            </FormItem>
            <Divider />
            <FormItem {...formItemLayout} label="规格参数">
              <SpecParams onChange={this.bindSpecParamsChange} data={paramsData}/>
            </FormItem>
            <FormItem {...formDetailItemLayout} label="详情">
              <MyEditor onChange={this.bindMyEditorChange} content={ goods.content }/>
            </FormItem>
            <FormItem {...submitFormLayout} style={{marginTop: 32}}>
              {/*<Button type="primary" htmlType="submit" loading={submitting}>
               提交
               </Button>*/}
              <Button type="primary" loading={false} onClick={this.handleSubmit}>
                提交
              </Button>
              <Button style={{marginLeft: 8}}><Link to={`/goods/goods-list`}>返回</Link></Button>
            </FormItem>
          </Form>
        </Card>
        <GoodsModal
          type = "coupon"
          dispatch={this.props.dispatch}
          modalVisible={modalVisible}
          handleHide={this.handleModalVisible}
          selectedRows = {selectedGoods}
          changeSelectedGoods = {this.changeSelectedGoods}
        />
      </PageHeaderLayout>
    );
  }
}
